//
//  WebViewController.swift
//  EasyDana
//
//  Created by mac on 2024/10/10.
//

import UIKit
import WebKit
import StoreKit
import RxSwift
class WebViewController: UIViewController {

    private let bag = DisposeBag()
    var url: String!
    var webView: WKWebView!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.configView()
        // Do any additional setup after loading the view.
    }
    
    private let titlePublish = PublishSubject<String>()
    
    private func configView() {
        self.view.backgroundColor = UIColor.white
        let naviBar = NavigationBar()
        self.view.addSubview(naviBar)
        naviBar.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(47)
            make.top.equalTo(self.view.snp.topMargin)
        }
        naviBar.titleColor = UIColor.black
        naviBar.backColor = UIColor.black
        naviBar.backgroundColor = UIColor.white
        naviBar.backClicked.subscribe(onNext: { [weak self] _ in
            if self?.webView.canGoBack ?? false {
                self?.webView.goBack()
            } else {
                self?.navigationController?.popViewController(animated: true)
            }
        })
        .disposed(by: self.bag)
        
        self.navigationController?.delegate = self
        let configuration = WKWebViewConfiguration()
        configuration.userContentController.add(self, name: "tuneful")
        configuration.userContentController.add(self, name: "well")
        configuration.userContentController.add(self, name: "beyond")
        configuration.userContentController.add(self, name: "word")
        configuration.userContentController.add(self, name: "that")
        self.webView = WKWebView(frame: self.view.bounds, configuration: configuration)
        self.view.addSubview(self.webView)
        self.webView.navigationDelegate = self
        self.webView.scrollView.contentInsetAdjustmentBehavior = .never
        var absoluteURL = ""
        if (self.url.contains(where: {$0 == "?"})) {
            absoluteURL = self.url + "&" + HTTPManager.default.defaultParam
        } else {
            absoluteURL = self.url + "?" + HTTPManager.default.defaultParam
        }
        absoluteURL = absoluteURL.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? absoluteURL
        if let u = URL(string: absoluteURL) {
            let request = URLRequest(url: u)
            self.webView.load(request)
        }
        self.webView.snp.makeConstraints { make in
            make.bottom.left.right.equalToSuperview()
            make.top.equalTo(naviBar.snp.bottom)
        }
        self.titlePublish
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: { title in
                naviBar.title = title
            })
            .disposed(by: self.bag)
        Observable<Int>.interval(.seconds(1), scheduler: MainScheduler.instance)
            .take(until: self.rx.deallocated)
            .subscribe(onNext: { [weak self] second in
                self?.webView.evaluateJavaScript("document.title") { (result, error) in
                            if let title = result as? String {
                                self?.titlePublish.onNext(title)
                            }
                        }
            })
            .disposed(by: self.bag)
        
    }

}

extension WebViewController: WKScriptMessageHandler, WKNavigationDelegate {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        let body = message.body
        switch message.name {
        case "tuneful":
            self.navigationController?.popViewController(animated: true)
            break
        case "beyond":
            self.tabBarController?.tabBar.isHidden = false
            self.tabBarController?.selectedIndex = 0
            self.navigationController?.popToRootViewController(animated: false)
            break
        case "well":
            //带参跳页面
            if let body = message.body as? [String] {
                if let u = URL(string: body.first ?? "") {
                    self.jump(url: u)
                }
            }
            break
        case "that":
            //确认申请埋点调用方法
            UploadStasticManager.default.uploadRiskPoint(type: 9, beginTime: Date())
            break
        case "word":
            if #available(iOS 14.0, *) {
                if let scene = UIApplication.shared.connectedScenes.first as? UIWindowScene {
                    SKStoreReviewController.requestReview(in: scene)
                }
            } else {
                SKStoreReviewController.requestReview()
            }
            break
        case "setTitle":
            if let body = body as? String {
                struct TitleModel: Codable {
                    let value: String
                }
                if let data = body.data(using: .utf8) {
                    do {
                        let decoder = JSONDecoder()
                        let titles = try decoder.decode(TitleModel.self, from: data)
                        self.titlePublish.onNext(titles.value)
                    } catch {
                        
                    }
                }
            }
            break
        default:
            break
        }
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        
    }
}

extension WebViewController: UINavigationControllerDelegate {
    func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
        if !navigationController.children.contains(self) {
            let userContentController = self.webView.configuration.userContentController
            userContentController.removeScriptMessageHandler(forName: "tuneful")
            userContentController.removeScriptMessageHandler(forName: "well")
            userContentController.removeScriptMessageHandler(forName: "word")
            userContentController.removeScriptMessageHandler(forName: "beyond")
            userContentController.removeScriptMessageHandler(forName: "that")
        }
    }
}
